#start script
set auto_path [concat [pwd]/../../pkg/tkMD $auto_path ]
#start script
if {[lsearch $argv --DEBUG] >= 0 } {
set DEBUG true
} else {
set DEBUG false
}

## prequisite
if [ catch {package require tkMD 1.1}] { puts "$argv0 needs tkMD 1.1, please install it first!";exit}
namespace import SimTask::*
namespace import Path::*
if { $tcl_version < 8.5 } {
    puts "Cannot run, tkMD requires Tcl version higher than 8.5."
    exit
}

proc main {argc argv} {
global argv0
proc print_help {} {
    global argv0
    puts "Usage:\n $argv0 paramterfile anascript \[--peptide peptide1 peptide2\] \[ --petidelist peptidefile1 peptidefile2 ...\] " 
 puts "Input:\n"
 puts "    paramterfile : the file that was used to setup simulation (find example files in the current folder)."
 puts "    anascript : which template script is going to be used." 
 puts "    \[--scan-path \] : direcotry that contains  simulation trajectories."
 puts "    \[--scan-patten \] : patten used to determine parameter values from path."
 puts "    \[--templatepath \] : place to look for template files."
 puts "    \[--use-charmm \] : which charmm binary file is going to be used."
 puts "    \[--post-process PostProcessScript outputname \] : tclscript to post process data from trajectory analysis."
}
proc parse_cmd {} {
    global argc argv 
    if {$argc < 1} {
        puts "Paramter File is required!"
        print_help
        exit
    }
    #get options 
    set options [lsearch -all -glob $argv "--*" ]
    set i 0
    foreach idx  $options {
    set end [expr [lindex $options [expr $i+1]]-1]
    if {$end <0} {set end end}
    set name [lindex $argv $idx]
    set value [lrange $argv [expr $idx +1] $end]
    set Option($name) $value
    incr i
    }
    # do the parsing for required arguments
    # validate and load the parameter file 
    global parameterfile basepath 
    set parameterfile [lindex $argv 0]
    if ![file exists $parameterfile] {puts "Parameter File $parameterfile does not exist!";print_help;exit}
    set basename [lindex [split [file rootname $parameterfile] /] end]
    set SimTask::RunPath [pwd]/$basename 
    uplevel 1 "source $parameterfile"
    
    if [catch {set basepath [lindex $argv 1]}] {set basepath [pwd]}
    if [string match $basepath --*] {set basepath [pwd]} 
    # do the parsing for options 
    global peptides
    foreach name [lsort [array names Option]] {
        switch -nocase $name {
        --scan-pattern {
            global patten
            set patten [lindex $Option(--scan-pattern) 0]
        }
         --scan-path {
                set SimTask::RunPath [lindex $Option(--scan-path) 0]
                if ![file isdirectory ${SimTask::RunPath}] { 
                    puts "PDB path ${SimTask::RunPath} is not correct!"
                    print_help
                    exit
                }
                if ![file exists ${SimTask::RunPath}] {
                    puts "PDB path ${SimTask::RunPath} do not exist!"
                    print_help
                    exit
                }
         }
         --templatepath {
                set SimTask::TemplatePath [lindex $Option(--templatepath) 0]
                if ![file isdirectory ${SimTask::TemplatePath}] { 
                    puts "PDB path ${SimTask::TemplatePath} is not correct!"
                    print_help
                    exit
                }
                if ![file exists ${SimTask::TemplatePath}] {
                    puts "PDB path ${SimTask::TemplatePath} do not exist!"
                    print_help
                    exit
                }
         }
         --jobpath {
                set SimTask::JobPath [lindex $Option(--jobpath) 0]
                if ![file isdirectory ${SimTask::JobPath}] { 
                    puts "PDB path ${SimTask::JobPath} is not correct!"
                    print_help
                    exit
                }
                if ![file exists ${SimTask::JobPath}] {
                    puts "PDB path ${SimTask::JobPath} do not exist!"
                    print_help
                    exit
                }
         }
         --skip {
                global skip 
                set skip [lindex $Option(--skip) 0] 
         }
         --ana-dcd {
            global dcdfile
            set dcdfile [lindex $Option(--ana-dcd) 0] 
         }
         --ana-script {
            global anascript
            set anascript [lindex $Option(--ana-script) 0] 
         }
         --use-charmm {
               set SimTask::Charmmbin [lindex $Option(--use-charmm) 0]
         }
        }
    }
}

#setup default parameters
global type temp thick ionc anfr preptime eqltime peptides orientation anascript
set type {water anionic neutral} 
set temp 298
set membrane dmpc
array set ThickDict { dlpc 19.5 dmpc 23.5 dopc 26 popc 27 }
set thick @ThickDict(@membrane)
set ionc 0.1
set anfr 0.3
set preptime 0.001
set eqltime 0.001
set orientation { o0 }
set peptides {}
set npeptide 1
set nreplica 4
set docleanning false
parse_cmd
VarSpace options { type membrane temp  thick  ThickDict ionc anfr orientation preptime eqltime }
#validate 
if [catch {set binpath [exec which $SimTask::Charmmbin]} ] {
    puts "Charmm Binary file does not exist or is not set up correctly!"
    print_help
    exit
}

set timestamp [clock format [clock seconds] -format "%b %d %y - %T"]
puts "Start trajectory analyze with { $argv0 $argv } @ $timestamp "
puts "==============================================================="
printEnv
puts "==============================================================="
puts "Parameters used for simulations: "
puts "==============================================================="
foreach var $options(*vars) {
   puts "$var = $options(def,$var)"
}
puts "==============================================================="
puts "Path parsing pattern:"
puts $pattern
puts "==============================================================="
# analysis code begins here

ana $SimTask::RunPath $dcdfile $anascript options $pattern --combinejob orientation i --skip { ![file exists eql_min.crd] } --post { grep 'alpha' traj.out > $dcdfile.2nd.dat.temp ;rm traj.out }
waitfor ana 
rmfiles $SimTask::RunPath  traj.out


#post process

#get 2nd strcuture from trajectory analysis.
proc getHelicity { input output } {
    set ifile [open $input r]
    set ofile [open $output w]
    set i 1
    puts $ofile "## I alpha% beta%"
    foreach line [split [read $ifile] \n] {
        set result [regexp -all -inline -- {\(\s+(\d+)\%\)} $line ]
        if {[llength $result] != 4} {continue }
        set alpha [lindex $result 1]
        set beta [lindex $result 3]
        puts $ofile "$i $alpha $beta"
        incr i
    }
    close $ofile
    close $ifile
}

foreach secfile [Path::searchfiles $SimTask::RunPath $dcdfile.2nd.dat.temp] {
    set dir [file dirname $secfile]
    getHelicity $secfile $dir/$dcdfile.2nd.dat
    exec rm $secfile
}


}

# execuate 
if [catch {main $argc $argv } error ] {
    if $DEBUG { puts $errorInfo } else { puts $error} 
}

exit 








